<!--
 * @Author: luojiajun
 * @Email: company.kachun@gmail.com
 * @Date: 2021-06-29 19:26:39
 * @FilePath: /src/views/dataManagement/system/user/components/UserRulesApiModal.vue
 * @LastEditTime: 2021-07-21 15:00:22
 * @LastEditors: luojiajun
-->
<template>
    <el-dialog title="编辑API服务权限" :visible.sync="dialogVisible">
        <div class="user-rules-api">
            <div class="user-rules-api-header">
                <el-input
                    placeholder="输入关键字进行过滤"
                    suffix-icon="el-icon-search"
                    v-model="keyword"
                ></el-input>
            </div>
            <div class="user-rules-api-table">
                <div class="user-rules-api-table__header">
                    <div class="user-rules-api-table__header--th"></div>
                    <div class="user-rules-api-table__header--th">管理</div>
                    <div class="user-rules-api-table__header--th">订阅</div>
                </div>
                <el-tree
                    ref="tree"
                    :data="treeData"
                    node-key="id"
                    default-expand-all
                    :expand-on-click-node="false"
                    :filter-node-method="filterNode"
                >
                    <div
                        class="custom-tree-node user-rules-api-table__main"
                        slot-scope="{ node, data }"
                    >
                        <div class="user-rules-api-table__main--td">
                            {{ data.dirName }}
                        </div>
                        <!-- TODO 全选和反选 -->
                        <div class="user-rules-api-table__main--td">
                            <el-checkbox-group 
                                v-model="data.data.isManage" 
                                @change="(value)=>{ filterSelect(data, value, node, 'isManage') }"
                            >
                                <el-checkbox label="1">
                                    <span v-if="!data.isTable">全选</span>
                                    <span>{{ "" }}</span>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                        <div class="user-rules-api-table__main--td">
                            <el-checkbox-group
                                v-model="data.data.isSubscribe"
                                @change="(value)=>{ filterSelect(data, value, node, 'isSubscribe') }"
                            >
                                <el-checkbox label="1">
                                    <span v-if="!data.isTable">全选</span>
                                    <span>{{ "" }}</span>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                </el-tree>
            </div>
        </div>

        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
import { editApiRole, getApiRole } from "@/api/dataManagement/system/user";

export default {
    name: "UserRulesApiModal",
    model: {
        prop: "visible",
        event: "change"
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        userId: {
            type: String,
            default: ""
        }
    },
    data() {
        return {
            loading: false,
            keyword: "",
            treeData: [],
        };
    },
    watch: {
        keyword(val) {
            this.$refs.tree.filter(val);
        },
        dialogVisible(value) {
            if (value) {
                this.getApiRole();
            }
        }
    },
    computed: {
        dialogVisible: {
            get() {
                return this.visible;
            },
            set(newValue) {
                this.$emit("change", newValue);
            }
        }
    },
    methods: {
        filterNode(value, data) {
            if (!value) return true;
            return data.dirName.indexOf(value) !== -1;
        },
        filterSelect(data, value, node, field) {
            // 选中字段
            if (node.level === 2) {
                let selected = this.isSelectedAllChildNodes(node.parent.data.children, field)
                node.parent.data.data[field] = selected
                return
            }
            // 选中表
            if (node.level === 1) {
                this.toggleSelectedAllChildNodes(node.data.children, field, value == 1)
                return
            }
        },
        /**
         * 判断是否选中所有子节点
         */
        isSelectedAllChildNodes(childNodes, field) {
            let isValid = true
            for (let i = 0; i < childNodes.length; i++) {
                const childNode = childNodes[i];
                if (!childNode.data[field].length || childNode.data[field] != 1) {
                    isValid = false
                    break;
                }
            }
            return isValid
        },
        /**
         * 全选/反选
         */
        toggleSelectedAllChildNodes(childNodes, field, selected) {
            for (let i = 0; i < childNodes.length; i++) {
                const childNode = childNodes[i];
                childNode.data[field] = selected ? ['1'] : []
            }
        },
        getApiRole() {
            getApiRole({ userId: this.userId })
                .then(res => {
                    if (res.code === 200) {
                        this.initTableData(res.data)
                    }
                })
                .catch(() => {});
        },
        initTableData(tree) {
            // 获取用户树节点
            let treeData = JSON.parse(
                JSON.stringify(tree.children)
            );

            for (let i = 0; i < treeData.length; i++) {
                const item = treeData[i];
                // 重置后端接口数据格式，防止报错
                for (let i = 0; i < item.children.length; i++) {
                    const child = item.children[i];
                    if (child.data.isManage.length && child.data.isManage[0] != 1) {
                        child.data.isManage = []
                    }
                    if (child.data.isSubscribe.length && child.data.isSubscribe[0] != 1) {
                        child.data.isSubscribe = []
                    }
                }
                // 判断是否需要勾选全选
                item.data = {
                    isManage: this.isSelectedAllChildNodes(item.children, 'isManage') ? ['1'] : [],
                    isSubscribe: this.isSelectedAllChildNodes(item.children, 'isSubscribe') ? ['1'] : []
                }
            }

            this.treeData = treeData
        },
        submitForm() {
            if (this.loading) return
            this.loading = true

            let tmpChildNodes = this.treeData.map(item => item.children)
            let childNodes = []
            for (let i = 0; i < tmpChildNodes.length; i++) {
                const item = tmpChildNodes[i];
                childNodes = childNodes.concat(item)
            }
            let postData = {
                userId: Number(this.userId),
                userApiEditInfoVos: []
            }
            for (let i = 0; i < childNodes.length; i++) {
                const item = childNodes[i];
                
                postData.userApiEditInfoVos.push({
                    apiId: Number(item.id),
                    isManage: item.data.isManage == 1 ? 1 : 0,
                    isSubscribe: item.data.isSubscribe == 1 ? 1 : 0,
                })
            }

            editApiRole(postData).then(res => {
                this.$emit('success')
                this.dialogVisible = false
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        }
    }
};
</script>

<style lang="scss" scoped>
.user-rules-api {
    &-header {
        margin-bottom: 20px;
    }

    &-table {
        max-height: 500px;
        overflow: auto;
        border: 1px solid #e6e6e6;
        user-select: none;

        &__header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            text-align: center;
            border-bottom: 1px solid #e6e6e6;

            &--th {
                padding: 0 10px;
                height: 50px;
                line-height: 50px;
                background: #f5f6fa;
                color: #1e1e1e;
                font-size: 16px;
                font-weight: 500;

                &:first-child {
                    flex: 1;
                }

                &:not(:first-child) {
                    width: 100px;
                    border-left: 1px solid #e6e6e6;
                }
            }
        }

        &__main {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e6e6e6;

            &--td {
                height: 40px;
                line-height: 40px;
                font-size: 16px;

                &:first-child {
                    flex: 1;
                    width: 600px;
                    padding-right: 10px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;   
                }

                &:not(:first-child) {
                    width: 100px;
                    text-align: center;
                    border-left: 1px solid #e6e6e6;
                }

                .el-checkbox {
                    width: 14px;
                    display: inline;
                }
            }
        }
    }

    ::v-deep {
        .el-tree-node:last-child {
            .custom-tree-node {
                margin-bottom: 2px;
            }
        }
    }

    ::v-deep .el-tree-node__content {
        height: 40px;
        line-height: 40px;
    }
}
</style>
